<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/6/1
 * Time: 上午10:31
 */

namespace app\api\controller;


use app\common\model\Agent;
use app\common\model\CardConsume;
use app\common\model\CardCzgive;
use app\common\model\CardGeneral;
use app\common\model\CardMember;
use app\common\model\CardQrcode;
use app\common\model\CardUserFee;
use app\common\model\CardUserGet;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\System;
use app\common\model\WxOpen;
use think\Controller;
use Wechat\Wxobjopen;

class Cardinfo extends Pub
{

    public function _unsetNull($arr){
        if($arr !== null){
            if (is_object($arr)){
                $arr = json_encode($arr,JSON_UNESCAPED_UNICODE);
                $arr = json_decode($arr,true);
            }
            if(is_array($arr)){
                if(!empty($arr)){
                    foreach($arr as $key => $value){
                        if($value === null){
                            $arr[$key] = '';
                        }else{
                            $arr[$key] = $this->_unsetNull($value);      //递归再去执行
                        }
                    }
                }
            }else{
                if($arr === null){ $arr = ''; }         //注意三个等号
            }
        }else{ $arr = ''; }
        return $arr;
    }


    //会员列表
    public function carduserlist($param)
    {
        try {
            $CardUserGet = new CardUserGet();
            $mids = $this->getmidlist('mid', $param['merchantid']);
            $mid = implode(',', $mids);
            $map['a.mid'] = array('in', $mid);
            $map['a.statu'] = 0;
            $map['a.have'] = 1;
            $map['a.fire'] = 1;
            $map['a.gs_mid']=array('in',"0,".$param['merchantid']);
            $map['a.card_type'] = 'MEMBER_CARD';
            $map['a.phone|a.code|a.old_code'] = array('like', '%' . $param['search_val'] . '%');
            $page = ($param['page'] - 1) * 10;

            $cardlist = $CardUserGet->alias('a')
                ->join('wn_card_fans f', 'f.openid=a.openid', 'left')
                ->where($map)
                ->field('a.id,a.card_type,f.head_url,f.nickname,a.code,a.name,a.sex as sex,f.sex as sexs,a.fire,
                f.statu,a.bonus,a.add_bonus,a.use_bonus,a.balance,a.add_balance,a.use_balance,a.phone,a.frequency,a.create_time,a.birthday,a.rank_name')
                ->order('a.id desc')->limit($page, 10)->select();
            $total = $CardUserGet->alias('a')->where($map)->count();
            if ($cardlist) {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'SUCCESS';
                $rarr['result_msg'] = '';
                $rarr['total'] = $total;
                $rarr['info'] = $this->_unsetNull($cardlist);
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = '获取失败';
                $rarr['info'] = [];
            }
        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;

    }

    //会员卡充值/消费记录
    public function cardreportlist($param)
    {
        try {
            $CardUserFee = new CardUserFee();
            $page = ($param['page'] - 1) * 10;
            $map['type'] = $param['report_type'];
            $map['mid'] = $param['merchantid'];
            $cardczlist = $CardUserFee->where($map)->limit($page, 10)->order('id desc')->select();
            $total = $CardUserFee->where($map)->count();
            if ($cardczlist) {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'SUCCESS';
                $rarr['result_msg'] = '';
                $rarr['total'] = $total;
                $rarr['info'] = $cardczlist;
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = '获取失败';
                $rarr['info'] = [];
            }
        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;

    }

    //会员卡单用户核销/充值记录
    public function carduserreportlist($param)
    {

        try {
            $CardUserGet = new CardUserGet();
            $CardUserFee = new CardUserFee();
            $page = ($param['page'] - 1) * 10;
            $map['type'] = $param['report_type'];
            $start_time = strtotime($param['start_time']);
            $end_time = strtotime($param['end_time']);
            if ($start_time == "" && $end_time == "") {
                $map['create_time'] = array('between', [0, time()]);
            } elseif ($start_time !== "" && $end_time == "") {
                $map['create_time'] = array('between', [$start_time, time()]);
            } elseif ($start_time == "" && $end_time !== "") {
                $map['create_time'] = array('between', [0, $end_time]);
            } else {
                $map['create_time'] = array('between', [$start_time, $end_time]);
            }
            $map['mid'] = $param['merchantid'];
            if (!empty($param['code'])) {
                $map['code'] = $param['code'];
            }
            $map['num'] = ['neq',0];
            $cardczlist = $CardUserFee->where($map)->limit($page, 10)->order('id desc')->select();
            $total = $CardUserFee->where($map)->count();
            foreach ($cardczlist as $k => $v) {
                $cardcz[$k]['id'] = $v['id'];
                $cardcz[$k]['balance'] = $v['num'];
                $cardcz[$k]['create_time'] = $v['create_time'];
                $cardcz[$k]['code'] = $v['code'];
                $cardcz[$k]['device_id'] = $v['action_user'];
                $cardcz[$k]['card_name'] = $CardUserGet->where(array('code'=>$v['code']))->value('name');;
            }
            if (isset($cardcz)) {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'SUCCESS';
                $rarr['result_msg'] = '';
                $rarr['total'] = $total;
                $rarr['info'] = $cardcz;
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = '获取失败';
            }
        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;

    }

    //卡券核销记录
    public function cardqreportlist($param)
    {
        try {
            $CardConsume = new CardConsume();
            $CardGeneral = new CardGeneral();
            $page = ($param['page'] - 1) * 10;
            $map['mid'] = $param['merchantid'];
            $start_time = strtotime($param['start_time']);
            $end_time = strtotime($param['end_time']);
            if ($start_time == "" && $end_time == "") {
                $map['create_time'] = array('between', [0, time()]);
            } elseif ($start_time !== "" && $end_time == "") {
                $map['create_time'] = array('between', [$start_time, time()]);
            } elseif ($start_time == "" && $end_time !== "") {
                $map['create_time'] = array('between', [0, $end_time]);
            } else {
                $map['create_time'] = array('between', [$start_time, $end_time]);
            }
            if(!empty($param['cardq_id'])){
                $CardGeneral=new CardGeneral();
                $map['card_id']=$CardGeneral->where('id',$param['cardq_id'])->value('card_id');
            }
            //       $map['con_openid'] = $params['con_openid'];
            $consumelist = $CardConsume->where($map)->limit($page, 10)->order('id desc')->select();
            $total = $CardConsume->where($map)->count();
            foreach ($consumelist as $k => $v) {
                $cardinfo = $CardGeneral->where(['card_id'=>$v['card_id']])->field('card_type,title,least_cost,reduce_cost')->find();
                $consume[$k]['code'] = $v['code'];
                $consume[$k]['card_type'] = getcardtype($cardinfo['card_type']);
                $consume[$k]['con_time'] = $v['create_time'];
                $consume[$k]['device_id'] = $v['con_username'];
                $consume[$k]['con_type'] = $v['hx_fs'];
                $consume[$k]['card_name'] = ['card_type'] =='CASH'?'满'.$cardinfo['least_cost'].'减'.$cardinfo['reduce_cost'].'代金券':$cardinfo['title'];;
//                $consume[$k]['action_user'] = $v['action_user'];
//                $consume[$k]['create_time'] = $v['create_time'];
//                $consume[$k]['hx_fs'] = $v['hx_fs'];
            }
            if ($consumelist) {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'SUCCESS';
                $rarr['result_msg'] = '';
                $rarr['total'] = $total;
                $rarr['info'] = $consume;

            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = '获取失败';
                $rarr['info'] = [];
            }
        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;

    }

    //获取会员卡开卡二维码
    public function getcardqrcode($params)
    {
        try {
            $Merchant = new Merchant();
            $CardMember = new CardMember();
            $top_mid = $Merchant->where(['id' => $params['merchantid']])->value('top_mid');
            $card = $CardMember->where(['top_mid' => $top_mid])->field('card_id')->find();
            $CardQrcode = new CardQrcode();
            $qrcode_url = $CardQrcode->where(['card_id' => $card['card_id'], 'mid' => $params['merchantid']])->value('qrcode_url');
            if ($qrcode_url) {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'SUCCESS';
                $rarr['result_msg'] = '获取成功';
                $rarr['qrcode_url'] = $qrcode_url;
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = '查询失败';
            }
        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;
    }

    //获取会员信息
    public function carduserinfo($param)
    {
        try {
            $Merchant = new Merchant();
            $Paylog = new Paylog();
            $top_mid = $Merchant->where('id', $param['merchantid'])->value('top_mid');
            $midlist = $Merchant->where('top_mid', $top_mid)->column('id');
            $mids = $midlist;
            $map['a.mid'] = array('in', $mids);
            $map['a.have'] = 1;
            $map['a.fire'] = 1;
            $map['a.phone|a.code|a.old_code'] = $param['code'];
            $map['a.card_type'] = 'MEMBER_CARD';
            $CardUserGet = new CardUserGet();
            $card = $CardUserGet->alias('a')
                ->join('wn_card_fans f', 'f.openid=a.openid', 'left')
                ->field('a.mid,a.id,a.card_type,a.code,a.name,a.sex as sex,a.status,a.fire,f.head_url,f.nickname,f.statu,a.remark,
                a.bonus,a.add_bonus,a.use_bonus,a.balance,a.add_balance,a.use_balance,a.phone,a.frequency,a.create_time,a.birthday,a.rank_name,a.openid')
                ->where($map)->find();
            if ($card) {
                $maps['card_type'] = ['neq','MEMBER_CARD'];
                $maps['openid'] = $card['openid'];
                $maps['mid'] = array('in', $mids);
                $cardsnum = $CardUserGet->where($maps)->count('id');
                //END
                $maps1['mid'] = array('in', $mids);
                $maps1['openid'] = $card['openid'];
                $maps1['pay_statu'] = 1;
                $maps1['pay_fs'] = ['in',[0,2,8]];
                $maps1['pay_cate'] = ['neq','recharge'];
                $pay_fee = $Paylog->where($maps1)->sum('price');
                //END
                $cdata['openid']=$card['openid'];
                $cdata['remark']=$card['remark'];
                $cdata['pay_fee'] = $pay_fee;
                $cdata['cards_num'] = $cardsnum;
                $cdata['name']=$card['name']==''?$card['nickname']:$card['name'];
                $cdata['nickname']=$card['nickname'];
                $cdata['head_url']=$card['head_url'];
                $cdata['phone']=$card['phone'];
                $cdata['rank_name']=$card['rank_name'];
                $cdata['merchantid']=$card['mid'];
                $cdata['balance']=$card['balance'];
                $cdata['add_balance']=$card['add_balance'];
                $cdata['bonus']=$card['bonus'];
                $cdata['add_bonus']=$card['add_bonus'];
                $cdata['create_time']=$card['create_time'];
                $cdata['code']=$card['code'];
                $cdata['birthday']=$card['birthday'];
                $cdata['status']=$card['status'];
                //END
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'SUCCESS';
                $rarr['result_msg'] = "获取成功";
                $rarr['info'] = $this->_unsetNull($cdata);
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = '会员卡不存在';
            }
        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;
    }

    //卡券信息
    /*
     * $params['merchid'] / $params['code'] /
     * */
    public function cardqinfo($params)
    {
        try {
            //   return json($params);
            $Merchant = new Merchant();
            $top_mid = $Merchant->where('id', $params['merchantid'])->value('top_mid');
            $midlist = $Merchant->where('top_mid', $top_mid)->field('id')->select();
            foreach ($midlist as $k => $v) {
                $midarr[] = $v['id'];
            }

            $mid = implode(',', $midarr);
            $map['mid'] = ['in', $mid];
            $map['top_mid'] = $top_mid;
            $map['code'] = $params['code'];
            $map['card_type'] = ['neq', 'MEMBER_CARD'];
            $CardUserGet = new CardUserGet();
            $CardGeneral = new CardGeneral();
            //用户
            $userinfo = $CardUserGet->where($map)->field('card_id,code,create_time,have,statu')->find();

            if ($userinfo) {
                if ($userinfo['statu'] == 0) {
                    if ($userinfo['have'] == 1) {
                        $mab['card_id'] = $userinfo['card_id'];
                        $cardinfo = $CardGeneral->where($mab)->field('title,brand_name,logo_url,card_type')->find();
                        $brand_name = $Merchant->where(['id' => $params['merchantid']])->value('merchant');
                        //卡券详情
                        $userinfos['card_id']=$userinfo['card_id'];
                        $userinfos['code']=$userinfo['code'];
                        $userinfos['create_time']=$userinfo['create_time'];
                        $userinfos['have']=$userinfo['have'];
                        $userinfos['statu']=$userinfo['statu'];
                        $userinfos['title'] = $cardinfo['title'];
                        $userinfos['merchantname'] = $brand_name;
                        $userinfos['logo_url'] = $cardinfo['logo_url'];
                        $userinfos['card_type'] = $cardinfo['card_type'];
                        //返回核销状态    0可用/1不可用
                        $userinfos['consume_statu'] = $this->consumestatu($userinfo['card_id'], $userinfo['code']);
                        $rarr['return_code'] = "SUCCESS";
                        $rarr['return_msg'] = 'ok';
                        $rarr['result_code'] = 'SUCCESS';
                        $rarr['result_msg'] = "获取成功";
                        $rarr['info'] = $userinfos;
                    } elseif ($userinfo['have'] == 0) {
                        $rarr['return_code'] = "SUCCESS";
                        $rarr['return_msg'] = 'ok';
                        $rarr['result_code'] = 'FAIL';
                        $rarr['result_msg'] = "卡券状态异常";
                    }
                } elseif ($userinfo['statu'] == 2) {
                    $rarr['return_code'] = "SUCCESS";
                    $rarr['return_msg'] = 'ok';
                    $rarr['result_code'] = 'FAIL';
                    $rarr['result_msg'] = "该卡券已核销";
                }
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = 'ok';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = "卡券编号不存在";
            }
        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;
    }
    //核销状态
    /*
     * $card_id / $code
     * */

//获取充送规则
    public function cardczgive($param)
    {
        try {
            $mab['id'] = $param['merchantid'];
            $Merchant = new Merchant();
            $map['top_mid'] = $Merchant->where($mab)->value('top_mid');
            $map['statu'] = 1;
            $CardCz = new CardCzgive();
            $list = $CardCz->where($map)->select();
            $lcount = count($list);
            $CardGeneral = new CardGeneral();
            $res2 = [];
            $z1 = '';
            $z2 = '';
            if ($list) {
                foreach ($list as $k => $v) {

                    $card_id = $v['zs_card_id_all'];
                    $card_id2 = $v['zs_card_id'];
                    $z1="";
                    $z2="";
                    $resu = '';
                    if ($v['zs_money']) {
                        $z1 = "赠送" . $v['zs_money'] . "元";
                    }

                    if ($v['bonus']) {
                        $z2 = "+" . $v['bonus'] . "积分";
                    }
                    if ($card_id !== '' && $card_id !== null) {
                        $s = json_decode($card_id, true);
                        $ss = "";
                        foreach ($s as $ks => $vs) {
                            $ss .= $vs['zs_card_id'] . "|" . $vs['zs_no'] . ",";
                        }

                        $card_id_list = explode(',', rtrim($ss, ','));

                        $res = [];
                        foreach ($card_id_list as $ks => $vs) {
                            $ivs = explode('|', $vs);

                            if (filteroffcard($ivs[0]) == true) {

                                $res[$ks]['title'] = $CardGeneral->where('card_id', $ivs[0])->value('title');
                                $res[$ks]['zs_no'] = $ivs[1];
                            }

                        }
                        if (count($res) >= 1) {
                            $resu = '赠卡券:';
                            if (isset($res)) {
                                foreach ($res as $ks => $vs) {
                                    $resu .= $vs['title'] . "(" . $vs['zs_no'] . "张),";
                                }
                                $resu = rtrim($resu, ',');
                            }
                        }
                    } elseif ($card_id2 !== '' && $card_id2 !== null) {
                        $cardlist2 = explode(',', $card_id2);
                        foreach ($cardlist2 as $ks => $vs) {
                            if (filteroffcard($vs) == true) {

                                $res2[$ks] = $CardGeneral->where('card_id', $vs)->value('title');
                            }
                        }
                        if ($res2) {
                            $resu = '+卡券:';
                            $resu .= implode(',', $res2);
                        }
                    }
                    if ($k == 0) {
                        $data[$k]['id'] = 0;
                        $data[$k]['name'] = "请选择充值规则";
                    }
                    $data[$k + 1]['id'] = $v['id'];
                    $data[$k + 1]['name'] = "充值" . $v['cz_money'] . "元" . $z1 . $z2 . $resu;
                    if ($k + 1 == $lcount) {
                        $data[$k + 2]['id'] = "";
                        $data[$k + 2]['name'] = "其他金额";
                    }
                }

                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '获取成功';
                $rarr['result_code'] = 'SUCCESS';
                $rarr['result_msg'] = '获取成功';
                $rarr['info'] = $data;
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '获取失败';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = '获取失败';
            }

        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }

        return $rarr;
    }

    //获取充值金额
    /*
     * $param['id']  规则ID
     * */
    public function cardczgiveprice($param)
    {
        try {
            $mab['id'] = $param['merchantid'];
            $Merchant = new Merchant();
            $map['top_mid'] = $Merchant->where($mab)->value('top_mid');
            $map['id'] = $param['csid'];
            $CardCz = new CardCzgive();
            $info = $CardCz->where($map)->find();
            $data['price'] = $info['cz_money'];
            if ($info) {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '获取成功';
                $rarr['result_code'] = 'SUCCESS';
                $rarr['result_msg'] = '获取成功';
                $rarr['price'] = $info['cz_money'];
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '获取失败';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = '获取失败';
            }
        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;
    }

    //微信API参数  根据card_id获取
    public function options($card_id)
    {
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $mid = $CardMember->where('card_id', $card_id)->value('mid');
        if ($mid) {
            $map['id'] = $mid;
        } else {
            $map['id'] = $CardGeneral->where('card_id', $card_id)->value('mid');
        }
        $merchantinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
        $users = $WxOpen->where($mab)->find();
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

}